<route lang="json5">
{
  style: {
    navigationBarTitleText: '人气榜',
  },
}
</route>
<template>
  <view class="popularity-ranking-page min-h-screen bg-gray-50 pb-20">
    <view class="bg-white sticky top-0 z-10 shadow-sm">
      <view class="w-full no-scrollbar p-2 shadow">
        <scroll-view class="scroll no-scrollbar mt-1" scroll-x="true">
          <view v-for="category in mainCategoryList" @click="changeCategory(category.id)" :key="category.id"
            class="item">
            <view class="w-12 h-12 rounded-full shadow-md flex items-center justify-center mb-1"
              :class="mainCategoryId == category.id ? 'bg-orange-100' : 'bg-gray-100'">
              <image :src="category.image" :alt="category.cateName" class="w-8 h-8 rounded-full object-contain" />
            </view>
            <view class="text-xs w-full text-center text-gray-700"
              :class="mainCategoryId == category.id ? 'text-orange-500' : 'text-gray-600'">
              {{ category.cateName }}
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <view class="relative p-2 h-36 flex flex-col justify-center items-center">
      <image class="absolute w-full h-full top-0 left-0 z-0" :src="config.value" mode="scaleToFill" />
      <view class="text-xl font-bold text-white relative z-1">
        上饶百社区"{{ getMainCategoryName(mainCategoryId) }}"人气榜
      </view>
      <view class="text-sm text-white mt-1 relative z-1">摒弃刷好评，只做真实推荐！</view>
    </view>

    <view class="bg-white p-2 mt-2">
      <view class="flex bg-gray-100 rounded-lg p-1 mb-4">
        <view v-for="(rankType, index) in rankingTypes" :key="index"
          class="flex-1 py-1.5 text-center text-sm font-medium rounded-lg transition-colors" :class="rankType.value === queryParams.type
            ? 'bg-white text-orange-500 shadow-sm'
            : 'text-gray-600'
            " @click="changeType(rankType.value)">
          {{ rankType.label }}
        </view>
      </view>

      <view class="flex items-center mb-4 overflow-x-auto hide-scrollbar">
        <view class="text-sm text-gray-500 mr-2 whitespace-nowrap">评级：</view>
        <view class="flex space-x-2">
          <view v-for="(rating, index) in visibleRatings" :key="index"
            class="px-3 py-1 text-sm rounded-full whitespace-nowrap" :class="queryParams.grade === rating.value
              ? 'bg-orange-500 text-white'
              : 'bg-gray-100 text-gray-600'
              " @click="changeGrade(rating.value)">
            {{ rating.label }}
          </view>
        </view>
      </view>

      <view v-if="showMoreRatings" class="flex items-center mb-4 ml-12 space-x-2">
        <view v-for="(rating, index) in hiddenRatings" :key="index"
          class="px-3 py-1 text-sm rounded-full whitespace-nowrap" :class="selectedRating === rating.value
            ? 'bg-orange-500 text-white'
            : 'bg-gray-100 text-gray-600'
            " @click="selectedRating = rating.value">
          {{ rating.label }}
        </view>
      </view>

      <view class="flex items-center overflow-x-auto hide-scrollbar" v-if="subCategoryList.length > 0">
        <view class="text-sm text-gray-500 mr-2 whitespace-nowrap">分类：</view>
        <view class="flex space-x-2">
          <view v-for="(cuisine, index) in subCategoryList" :key="index"
            class="px-3 py-1 text-sm rounded-full whitespace-nowrap" :class="subCategoryId === cuisine.id
              ? 'bg-orange-500 text-white'
              : 'bg-gray-100 text-gray-600'
              " @click="changeSub(cuisine.id)">
            {{ cuisine.cateName }}
          </view>
        </view>
      </view>
    </view>

    <view class="p-2">
      <view v-if="storeList.length === 0" class="text-center py-12">
        <i class="iconfont icon-gouwudai w-16 h-16 text-12 text-gray-300 mx-auto mb-4"></i>
        <view class="text-gray-500">暂无符合条件的{{ getMainCategoryName(mainCategoryId) }}</view>
      </view>

      <view v-else class="space-y-4">
        <view v-for="(place, index) in storeList" :key="index" @click="toStorePage(place)"
          class="bg-white rounded-lg shadow-sm overflow-hidden relative">
          <view
            class="absolute top-0 left-0 z-10 w-8 h-8 rounded-full bg-orange-500 text-white flex items-center justify-center font-bold shadow-md">
            {{ index + 1 }}
          </view>

          <view class="flex border-l-orange-500 items-center gap-2">
            <view class="w-2"></view>
            <image :src="place.picture" :alt="place.name" class="w-30 h-30 object-cover" />
            <view class="flex-1 p-2">
              <view class="font-bold text-gray-800 line-clamp-1">{{ place.name }}</view>

              <view class="flex items-center mt-1">
                <text class="text-xs px-1.5 py-0.5 bg-gray-100 text-gray-600 rounded">
                  {{ place.cname }}
                </text>
                <text class="text-sm text-gray-500 ml-2">¥{{ place.perCapita }}/人</text>
              </view>

              <view class="flex items-center mt-2">
                <view class="flex flex-row justify-start items-center gap-2">
                  <view class="text-sm h-8 leading-8">
                    评价：
                    <text class="px-2 py-0.5 rounded text-xs text-white" :class="{
                      'bg-green-500': place.grade === '优',
                      'bg-blue-500': place.grade === '良',
                      'bg-yellow-500': place.grade === '中',
                      'bg-red-500': place.grade === '及格',
                    }">
                      {{ place.grade }}
                    </text>
                  </view>

                  <view class="text-sm h-8 leading-8">
                    评分：
                    <text class="text-orange-500 text-xl ml-1">{{ place?.score?.toFixed(2) }}</text>
                  </view>
                </view>
                <text class="text-orange-500 text-sm ml-1">{{ place.rating }}</text>
              </view>

              <view class="flex justify-between items-center mt-3">
                <view class="flex items-center">
                  <i class="iconfont icon-xihuan w-4 text-orange-500 mr-1"></i>
                  <text class="text-sm text-gray-600">{{ place.assistNumber }}人推荐</text>
                </view>

                <view class="px-3 py-1 bg-orange-500 text-white text-xs rounded-full"
                  @click.stop="openSupportModal(place)">
                  助力
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view v-if="showImagePreview" class="fixed inset-0 bg-black/90 z-50 flex items-center justify-center"
      @click="showImagePreview = false">
      <view class="relative w-full max-w-lg">
        <image :src="previewImage" alt="Place preview" class="w-full" />
        <view class="absolute top-4 right-4 p-2 bg-black/50 rounded-full text-white" @click="showImagePreview = false">
          <i class="w-5 h-5 iconfont icon-guanbi1 text-5 leading-5 text-gray-500" />
        </view>
      </view>
    </view>

    <view v-if="showSupportModal" class="fixed inset-0 bg-black/60 z-40 flex items-center justify-center p-2"
      @click="showSupportModal = false">
      <view class="bg-white rounded-lg w-full max-w-xs p-2" @click.stop>
        <view class="text-center font-bold text-gray-800 mb-3">确认助力</view>
        <view class="text-center text-gray-600 mb-4">
          是否确定为"{{ selectedStore.name }}"助力？
        </view>
        <view class="flex space-x-3">
          <view class="flex-1 py-2 border text-center border-gray-300 text-gray-600 rounded-lg"
            @click="showSupportModal = false">
            取消
          </view>
          <wd-button open-type="share" class="flex-1 py-2 bg-orange-500 text-center text-white rounded-lg"
            @click="confirmSupport">
            确定
          </wd-button>
        </view>
      </view>
    </view>

    <view v-if="showMapModal" class="fixed inset-0 bg-black/60 z-40 flex items-center justify-center p-2"
      @click="showMapModal = false">
      <view class="bg-white rounded-lg w-full max-w-md max-h-[80vh] overflow-hidden" @click.stop>
        <view class="p-2 border-b border-gray-100 flex justify-between items-center">
          <view class="font-bold text-gray-800">{{ getMainCategoryName(mainCategoryId) }}分布</view>
          <view @click="showMapModal = false">
            <i class="w-5 h-5 iconfont icon-guanbi1 text-5 leading-5 text-gray-500" />
          </view>
        </view>

        <view class="p-2">
          <view class="bg-gray-100 h-64 rounded-lg flex items-center justify-center">
            <view class="text-center">
              <i class="iconfont icon-dingwei w-10 h-10 text-10 text-gray-400 mx-auto mb-2" />
              <view class="text-gray-500">地图加载中...</view>
            </view>
          </view>

          <view class="mt-4 flex flex-wrap gap-3">
            <view class="flex items-center">
              <view class="w-3 h-3 rounded-full bg-green-500 mr-1"></view>
              <text class="text-xs text-gray-600">优秀</text>
            </view>
            <view class="flex items-center">
              <view class="w-3 h-3 rounded-full bg-blue-500 mr-1"></view>
              <text class="text-xs text-gray-600">良好</text>
            </view>
            <view class="flex items-center">
              <view class="w-3 h-3 rounded-full bg-yellow-500 mr-1"></view>
              <text class="text-xs text-gray-600">中等</text>
            </view>
            <view class="flex items-center">
              <view class="w-3 h-3 rounded-full bg-red-500 mr-1"></view>
              <text class="text-xs text-gray-600">差评</text>
            </view>
          </view>

          <view class="mt-4 max-h-40 overflow-y-auto">
            <view v-for="(place, index) in filteredPlaces.slice(0, 5)" :key="index"
              class="flex items-center py-2 border-b border-gray-100 last:border-0">
              <view class="w-5 h-5 rounded-full flex items-center justify-center text-xs text-white mr-2" :class="{
                'bg-orange-500': index < 3,
                'bg-gray-400': index >= 3,
              }">
                {{ index + 1 }}
              </view>
              <view class="flex-1">
                <view class="text-sm font-medium text-gray-800">{{ place.name }}</view>
                <view class="text-xs text-gray-500">{{ place.address }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { http } from '@/utils/http'
// Place Types
const mainCategoryList = ref([])
const subCategoryList = ref([])

const mainCategoryId = ref('')
const subCategoryId = ref('')
const storeList = ref([])
const bgimg = ref('')

const config = ref(null)

const getConfig = async () => {
  let res5 = await http.get('/api/config/list')
  if (res5.code == 200) {
    config.value = res5.data.list.filter((item) => item.code == 'bgimg')[0]
  }
}

const changeCategory = (id) => {
  mainCategoryId.value = id
  getCategory()
}

const setMainCategoryId = (type) => {
  mainCategoryId.value = type
  getSubCategory()
}

const getMainCategoryName = (type) => {
  const found = mainCategoryList.value.find((item) => item.id === type)
  return found ? found.cateName : ''
}

const initBg = async () => {
  let res5 = await http.get('/api/config/list')
  if (res5.code == 200) {
    bgimg.value = res5.data.list[2].value
  }
}

const getCategory = async () => {
  let res = await http.get('/api/home/categories', { pid: 0, type: 2 })
  if (res.code == 200) {
    mainCategoryList.value = res.data.categories
    if (mainCategoryList.value.length > 0) {
      if (!mainCategoryId.value) {
        mainCategoryId.value = mainCategoryList.value[0].id
      }
      getSubCategory()
    }
  }
}

const getSubCategory = async () => {
  let res = await http.get('/api/home/categories', { pid: mainCategoryId.value })
  if (res.code == 200) {
    subCategoryList.value = [
      {
        cateName: '全部',
        id: '',
      },
      ...res.data.categories,
    ]
    if (subCategoryList.value.length > 0) {
      subCategoryId.value = subCategoryList.value[0].id

      getStore()
    } else {
      subCategoryId.value = ''
      getStore()
    }
  }
}

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  type: 1,
  grade: '',
})

const total = ref(0)

const changeGrade = (grade) => {
  queryParams.value.pageNum = 1
  queryParams.value.grade = grade
  getStore()
}

const changeSub = (id) => {
  queryParams.value.pageNum = 1
  subCategoryId.value = id
  getStore()
}

const getStore = async () => {
  let res = await http.get('/api/store/list', {
    ...queryParams.value,
    classification: subCategoryId.value || mainCategoryId.value,
  })
  if (res.code == 200) {
    console.log('res', res)
    total.value = res.data.total

    if (queryParams.value.pageNum == 1) {
      storeList.value = res.data.list
    } else {
      storeList.value = storeList.value.concat(res.data.list)
    }
  }
}

onLoad(({ id }) => {
  if (id) {
    mainCategoryId.value = parseInt(id)
  }

  initBg()
  getCategory()
  getConfig()
})

onReachBottom(() => {
  if (storeList.length < total.value) {
    queryParams.value.pageNum = queryParams.value.pageNum + 1
    getStore()
  } else {
    uni.showToast({
      title: '没有更多了',
      icon: 'none',
      mask: false,
    })
  }
})

// Ranking Types
const rankingTypes = [
  { label: '人气榜', value: 1 },
  { label: '评级榜', value: 2 },
]

const changeType = (type) => {
  queryParams.value.pageNum = 1
  queryParams.value.type = type
  getStore()
}

const allRatings = [
  { label: '不限', value: '' },
  { label: '优', value: '优' },
  { label: '良', value: '良' },
  { label: '中', value: '中' },
  { label: '及格', value: '及格' },
]

const visibleRatings = computed(() => {
  return allRatings.slice(0, 3)
})

const hiddenRatings = computed(() => {
  return allRatings.slice(3)
})

const selectedRating = ref('all')
const showMoreRatings = ref(false)

const toStorePage = (store) => {
  uni.navigateTo({
    url: `/pages/store/detail?id=${store.id}`,
  })
}

const navigateTo = (url) => {
  uni.navigateTo({
    url,
  })
}

// Image Preview
const showImagePreview = ref(false)
const previewImage = ref('')

const openImagePreview = (image) => {
  previewImage.value = image
  showImagePreview.value = true
}

// Support Modal
const showSupportModal = ref(false)
const selectedStore = ref({})

const openSupportModal = (place) => {
  selectedStore.value = place
  showSupportModal.value = true
}

const confirmShare = async () => {
  uni.showShareMenu({
    title: '邻里生活荟',
    content: selectedStore.value.name,
    imageUrl: selectedStore.value.picture,
    path: `/pages/store/detail?id=${selectedStore.value.id}`,
  })
}

const confirmSupport = async () => {
  // 获取个人信息中的次数
  let resp = await http.get('/api/user/my')
  if (resp.code == 200) {
    console.log('resp.data', resp.data)

    let assist = resp.data.assist
    if (assist == 0) {
      let resp1 = await http.get('/api/user/assistSharing', { type: 2 })
      console.log('%c [ resp1 ]-469', 'font-size:13px; background:pink; color:#bf2c9f;', resp1)

      if (resp1.code == 200) {
        uni.showShareMenu({
          title: '邻里生活荟',
          content: selectedStore.value.name,
          imageUrl: selectedStore.value.picture,
          path: `/pages/store/detail?id=${selectedStore.value.id}`,
        })

        let res = await http({
          url: '/api/store/assistStore',
          method: 'get',
          data: {
            storeId: selectedStore.value.id,
          },
        })

        if (res.code == 200) {
          showSupportModal.value = false
          uni.showToast({
            title: '助力成功！',
            icon: 'none',
            mask: false,
          })

          queryParams.value.pageNum = 1
          getStore()
        } else {
          showSupportModal.value = false

          uni.showToast({
            title: res.msg,
            icon: 'none',
            mask: false,
          })
        }
      } else {
        showSupportModal.value = false

        uni.showToast({
          title: resp1.msg,
          icon: 'none',
          mask: false,
        })
      }
    } else {
      let res = await http({
        url: '/api/store/assistStore',
        method: 'get',
        data: {
          storeId: selectedStore.value.id,
        },
      })

      if (res.code == 200) {
        showSupportModal.value = false
        uni.showToast({
          title: '助力成功！',
          icon: 'none',
          mask: false,
        })

        queryParams.value.pageNum = 1
        getStore()
      } else {
        showSupportModal.value = false

        uni.showToast({
          title: res.msg,
          icon: 'none',
          mask: false,
        })
      }
    }
  }
}

const showMapModal = ref(false)

const goBack = () => {
  uni.navigateBack()
}

onShareAppMessage(() => {
  return {
    title: '邻里生活荟',
    content: selectedStore.value.name,
    imageUrl: selectedStore.value.picture,
    path: `/pages/store/detail?id=${selectedStore.value.id}`,
  }
})
onShareTimeline(() => {
  return {
    title: '邻里生活荟',
    content: selectedStore.value.name,
    imageUrl: selectedStore.value.picture,
    path: `/pages/store/detail?id=${selectedStore.value.id}`,
  }
})
</script>

<style scoped>
.hide-scrollbar {
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.hide-scrollbar::-webkit-scrollbar {
  display: none;
  /* Chrome, Safari, Opera */
}

.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.scroll {
  width: 750rpx;
  white-space: nowrap;
}

.item {
  display: inline-block;
  width: 100rpx;
  margin-right: 58rpx;
}
</style>
